<template>
    <a-select
            v-bind="$attrs"
            v-on="$listeners"
            v-model="localValue"
            :placeholder="placeholder"
            :filter-option="false"
            @popupScroll="handlepopupScroll"
            @search="handleSearch"
    >
        <a-select-option v-for="item in personList" :key="item.employeeId" :value="item.employeeId">
            <a-tooltip v-if="item.postPNames">
                <template slot="title">
                    <span>{{ item.postPNames }}</span>
                </template>
                {{ item.employeeName }}
            </a-tooltip>
            <span v-else>{{ item.employeeName }}</span>
          </a-select-option>
    </a-select>
</template>

<script>
  import {  getOneOrgUsers } from '@/api/commons.js'
  export default {
    model: {
      event: 'packageChange'
    },
    props: {
      userList: {
        type: Array,
        default() {
          return []
        }
      },
      valueKey: {
        type: String,
        default: 'userId'
      },
      placeholder: {
        type: String,
        default: '请选择'
      },
      // 组织ID根据组织ID查人
      // orgId: {
      //   type: [String, Number],
      //   default: ''
      // },
      // 双向绑定使用
      value: {
        type: [String, Number, Object, Array]
      },
      // 是否过滤重复的人员
      needFilterDuplicate: {
        type: Boolean,
        default: true
      },
      //如果是编辑，第一次不要重置绑定的值。。。。
      isEdit: {
        type: Boolean,
        default: () => true
      },
    },
    data() {
      return {
        nameLike: ''
      }
    },
    created() {
      if (this.$attrs.mode == 'multiple') {
        this.isMultiple = true
      }
      this.getPersonList()
    },
    watch: {
      orgId: {
        handler() {
          this.pageNumber = 1
          this.personList = []
          this.getPersonList()
        }
      }
    },
    computed: {
      localValue: {
        get() {
         console.log('get')
          let currentLabel
          let target = this.personList.find((item) => item.employeeId === this.value || item.userId === this.value)
          currentLabel = target && target.employeeName
          if (this.isMultiple) {
            target =
              this.personList.filter((item, index) => {
                return this.value?.includes(item.employeeId || item.userId)
              }) || []
            currentLabel = target.length && target.map((v) => v.employeeName)
          }
          this.$emit('personChanged', target || {})
          let noVal = this.isMultiple ? [] : void 0
          return this.value || noVal
        },
        set(val) {
          console.log('set')
          this.$emit('packageChange', val || this.value)
          let currentLabel
          let target = this.personList.find((item) => item.employeeId === val || item.userId === this.value)
          currentLabel = target && target.employeeName
          if (this.isMultiple) {
            target =
              this.personList.filter((item, index) => {
                return this.value?.includes(item.employeeId || item.userId)
              }) || []
            currentLabel = target.length && target.map((v) => v.employeeName)
          }
          this.$emit('personChanged', target || {})
        }
      }
    },
    data() {
      return {
        isCanClear: !this.isEdit, // 是否清除
        personList: [],
        isMultiple: false,
        pageNumber: 1
      }
    },
    methods: {
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      handleSearch(val) {
        this.nameLike = val
        this.personList = []
       this.getPersonList()
      },
      /**
       * @description: 滚动回调
       * @param {e} 事件对象
       * @return {void}
       */
     async handlepopupScroll(e) {
        const { target } = e
        if (Math.ceil(target.scrollTop + target.offsetHeight) >= target.scrollHeight) {
           this.pageNumber++
          await this.getPersonList()
        }
      },
      async getPersonList() {
        // if ( !this.orgId ) return
        // console.log(this.row, 'rpw')
        try {
         const data = { pageNumber: this.pageNumber, pageSize: 20, rootOrgId: '', nameLike:this.nameLike,  types: [0]}
          let   res = await getOneOrgUsers(data)
          let list =  []
            list = ((res.data && res.data.list) || []).map((item) => {
              item.postPNames = item.postPNames.join(",")
              item.employeeId = item[this.valueKey]
              item.employeeName = item.name
              return item
            })
          if (this.needFilterDuplicate) {
            const map = new Map()
            list = list.filter((item) => {
              if (map.get(item.employeeId)) {
                return false
              } else {
                map.set(item.employeeId, true)
                return true
              }
            })
            map.clear()
          }
          this.personList = [...this.personList,...list]
          this.$forceUpdate()
        } catch(error) {
          console.error(error.message)
          this.personList = []
        }
      }
    }
  }
</script>

<style>
</style>